package com.gjintel.auction.business.controller;

import com.gjintel.auction.business.model.AuctionInfo;
import com.gjintel.auction.business.model.RegAudit;
import com.gjintel.auction.business.service.IAuctionService;
import com.gjintel.auction.business.service.IRegAuditService;
import com.gjintel.framework.cache.InitCacheData;
import com.gjintel.framework.constant.Constant;
import com.gjintel.framework.dept.model.Dept;
import com.gjintel.framework.res.model.Resources;
import com.gjintel.framework.res.service.IResService;
import com.gjintel.framework.role.service.IRoleService;
import com.gjintel.framework.user.model.User;
import com.gjintel.framework.util.CommUtil;
import com.gjintel.framework.util.FileResUtil;
import com.gjintel.sdk.base.dao.Page;
import com.gjintel.sdk.base.dao.Sort;
import com.gjintel.sdk.util.FileDownload;
import com.gjintel.sdk.util.StringUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@RequestMapping("/auction/business/regAudit")
@Controller
@SuppressWarnings("unchecked")
public class RegAuditController {

    @Autowired
    private IRegAuditService regAuditService;

    @Autowired
    private IAuctionService auctionService;

    @Autowired
    private IResService resService;

    @Autowired
    private IRoleService roleService;

    /**
     * 产权流程
     */
    private static final String PROCESS_AUCTION_KEY = "auctionProcess";

    @RequestMapping("/bidderList")  //竞拍人列表
    public ModelAndView rightManagePage(HttpSession session, String auctionId) {
        ModelAndView mv = new ModelAndView("/auction/regAudit/reg-audit");
        mv.addObject("auctionId", auctionId);
        return mv;
    }

    @RequestMapping("/bidderDetailList")  //竞拍人详情列表
    public ModelAndView bidderDetailList(HttpSession session, String auctionId) {
        ModelAndView mv = new ModelAndView("/auction/regAudit/reg-audit-detail");
        mv.addObject("auctionId", auctionId);
        //项目报名详情
        List<RegAudit> regInfo = this.regAuditService.findOneByAuctionId(auctionId);
        for (RegAudit regAudit : regInfo){
            if (regAudit.getStatus()==0) {
                regAudit.setStatusName("申请中");
            }else if(regAudit.getStatus()==1){
                regAudit.setStatusName("未通过");
            }else if(regAudit.getStatus()==2){
                regAudit.setStatusName("已通过");
            }else {
                regAudit.setStatusName("未知");
            }
        }
        mv.addObject("regInfo", regInfo);
        return mv;
    }

    @RequestMapping("/list")
    @SuppressWarnings("unchecked")
    @ResponseBody
    public JSONObject list(String auctionId, HttpSession session, Page page, RegAudit regAudit, Sort sort) {
        User sUser = (User) session.getAttribute("loginUser");
        int loginUserType = 0;
        if (sUser.getId().equals("1")) {
            loginUserType = 1;
        }
        Dept loginDept = (Dept) InitCacheData.getInstance().getCacheData(InitCacheData.CacheType.DEPT).get(sUser.getDeptId());
        this.regAuditService.findAll(auctionId, page, regAudit, sort, loginUserType,loginDept.getpUnit());
        if (!page.getResult().isEmpty()) {
            Iterator<RegAudit> regIt = page.getResult().iterator();
            RegAudit temp = null;
            while (regIt.hasNext()) {
                temp = regIt.next();
                if (temp.getStatus()==0) {
                    temp.setStatusName("申请中");
                }else if(temp.getStatus()==1){
                    temp.setStatusName("未通过");
                }else if(temp.getStatus()==2){
                    temp.setStatusName("已通过");
                }else {
                    temp.setStatusName("未知");
                }
            }
        }
        return CommUtil.getPageJSONData(page, true);
    }

    @RequestMapping("/uploadPage")
    public ModelAndView uploadPage(HttpSession session, String id) {
        User sUser = (User) session.getAttribute("loginUser");
        ModelAndView mv = new ModelAndView("/auction/regAudit/data-upload");

        AuctionInfo ai = auctionService.get(AuctionInfo.class,id);

        mv.addObject("auctionId", ai.getId());
        mv.addObject("auctionName", ai.getAuctionName());
        mv.addObject("regId", sUser.getId());
        mv.addObject("regName", sUser.getLoginName());
        mv.addObject("status", 0);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        mv.addObject("regTime", sdf.format(new Date()));
        return mv;
    }

    @RequestMapping("/upload")
    public void upload(HttpServletRequest request, HttpServletResponse response, Integer functionFlog)
            throws IOException {
        PrintWriter out = response.getWriter();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 取得request中的文件,获取一个list集合
        MultipartFile file = multipartRequest.getFile("Filedata");
        // 得到文件的相对路径
        String relativePath = File.separator + "sign";
        String uploadPath = request.getSession().getServletContext().getRealPath("file_resource") + relativePath;
        File filePath = new File(uploadPath);
        // 判断文件夹是否存在，如果不存在给与创建出来
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        String fileName = file.getOriginalFilename();
        Resources res = new Resources();
        String exeName = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        res.setExeName(exeName);
        res.setFilePath(relativePath);
        res.setFileSize(file.getSize());
        res.setOldName(fileName);
//        res.setBusinessId();
        res.setFunctionFlog(0);// 设置文件功能类型(报名材料。。。。)
        FileResUtil.addFileRes(res); // 保存文件记录
        File newFile = new File(uploadPath, res.getId() + res.getExeName());
        file.transferTo(newFile);
        out.write(res.getId());
        out.flush();
        out.close();
    }

    @RequestMapping("/save")

    @ResponseBody
    public String save(HttpSession session,String uploadify, RegAudit regAudit){
        List<RegAudit> regAuditList = regAuditService.repeatSign(regAudit.getAuctionId(),regAudit.getRegId());
        AuctionInfo ai = auctionService.get(AuctionInfo.class,regAudit.getAuctionId());
        Resources res = resService.get(Resources.class,uploadify);
        if(regAuditList.size()>0){
            return Constant.UNSUCCESS;
        }else {
            RegAudit ra = regAuditService.findOneById(regAudit.getAuctionId(),regAudit.getRegId());
            if (ra!=null){
                if (ai.getAuctionStart().getTime()<new Date().getTime()){   //已开标，超时
                    return "overtime";
                }else {
                    ra.setUpdateTime(new Date());
                    ra.setStatus(0);
                    regAuditService.saveOrUpdate(ra);
                    List<Resources> resList = resService.findResources(ra.getId());
                    resService.remove(resList);
                    res.setBusinessId(ra.getId());
                    resService.saveOrUpdate(res);
                }
            }else {
                if (ai.getAuctionStart().getTime()<new Date().getTime()){   //已开标，超时
                    return "overtime";
                }else {
                    regAudit.setCreateTime(new Date());
                    regAuditService.save(regAudit);
                    res.setBusinessId(regAudit.getId());
                    resService.saveOrUpdate(res);
                }
            }
            return Constant.SUCCESS;
        }

    }

    @RequestMapping("/download")
    @ResponseBody
    public void download(String id, HttpSession session, HttpServletResponse response, HttpServletRequest request)throws IOException {
        List<Resources> list = resService.findByBusinessIdAndFlag(id,0);
        String basePath = session.getServletContext().getRealPath("/"); // 获取基本路径
        for (Resources res : list){
            String fileName = res.getOldName();
            String fileRealPath =basePath +"file_resource\\sign\\"+ res.getId() + res.getExeName();

            // 下载文件
            FileDownload.processDownload(fileRealPath, fileName, request, response);
        }


    }

    @RequestMapping("/successPrompt")
    @ResponseBody
    public ModelAndView prompt(HttpSession session, String id) {
        if (!StringUtil.isEmpty(id)) {
            ModelAndView mv = new ModelAndView("/auction/regAudit/audit-success-prompt");
            mv.addObject("id", id);

            return mv;
        }
        return null;
    }

    @RequestMapping("/pass")
    @ResponseBody
    public String pass(HttpSession session, String id){

        User suser = (User) session.getAttribute("loginUser");
        RegAudit regAudit = regAuditService.get(RegAudit.class,id);
        try{
            Date entryEnd = auctionService.get(AuctionInfo.class,regAudit.getAuctionId()).getAuctionStart();    //获取报名截止时间(竞拍开始时间)
            if (regAudit.getStatus()==2){
                return Constant.SAVE_UN_SUCCESS;
            }
            if (!StringUtil.isEmpty(regAudit.getAuctionId())){
                if(entryEnd.getTime()<new Date().getTime()){
                    return "overtime";
                }else {
                    regAudit.setAuditId(suser.getId());
                    regAudit.setStatus(2);
                    regAudit.setAuditTime(new Date());
                    this.regAuditService.saveOrUpdate(regAudit);

                    return Constant.SUCCESS;
                }
            }
            return Constant.UNSUCCESS;
        }catch (Exception e){

        }
        return Constant.UNSUCCESS;
    }

    /**
     * @description 报名审核不通过原因填写页面
     * @param session
     * @param id
     * @return ModelAndView
     */
    @RequestMapping("/failReson")
    @ResponseBody
    public ModelAndView failReason(HttpSession session, String id) {
        if (!StringUtil.isEmpty(id)) {
            ModelAndView mv = new ModelAndView("/auction/regAudit/audit-fail-reson-input");
            mv.addObject("id", id);
            RegAudit ra = regAuditService.get(RegAudit.class,id);
            mv.addObject("oldReasom", ra.getRefuseComment());
            return mv;
        }
        return null;
    }

    @RequestMapping("/unPass")
    @ResponseBody
    public String unPass(HttpSession session,RegAudit regAudit){
        RegAudit ra = regAuditService.get(RegAudit.class,regAudit.getId());
        if (ra.getStatus()==2){
            return Constant.SAVE_UN_SUCCESS;
        }
        try{
            Date entryEnd = auctionService.get(AuctionInfo.class,ra.getAuctionId()).getEntryEnd();    //获取报名截止时间
            User suser = (User) session.getAttribute("loginUser");
            if (!StringUtil.isEmpty(regAudit.getId()) || new Date().compareTo(entryEnd) <= 0 || regAudit.getRefuseComment().length()>0){
                ra.setAuditId(suser.getId());
                ra.setAuditTime(new Date());
                if (StringUtil.isEmpty(ra.getRefuseComment())){
                    ra.setRefuseComment("审核建议：" + regAudit.getRefuseComment());
                }else {
                    ra.setRefuseComment(ra.getRefuseComment()+"<br>审核建议："+regAudit.getRefuseComment());
                }
                ra.setStatus(1);       //1 不通过
                this.regAuditService.saveOrUpdate(ra);
                return Constant.SUCCESS;
            }
            return Constant.UNSUCCESS;
        }catch (Exception e){

        }
        return Constant.UNSUCCESS;

    }

    /**
     * @description 报名审核不通过原因详情
     * @param session
     * @param id
     * @return ModelAndView
     */
    @RequestMapping("/signStatus")
    @ResponseBody
    public ModelAndView signStatus(HttpSession session, String id) {
        User suser = (User) session.getAttribute("loginUser");
        if (!StringUtil.isEmpty(id)) {
            ModelAndView mv = new ModelAndView("/auction/regAudit/sign-status");
            RegAudit ra = regAuditService.findOneById(id,suser.getId());
            if (ra == null){
                mv.addObject("refuseComment", "此项目尚未报名，如需报名请及时提交资料！");
            }else {
                if (ra.getStatus()==0){
                    if (StringUtil.isEmpty(ra.getRefuseComment())){
                        mv.addObject("refuseComment", "报名待审核");     //第一次审核(申请中)
                    }else {
                        mv.addObject("refuseComment", ra.getRefuseComment()+"<br>报名待审核");       //多次审核
                    }

                }else if (ra.getStatus()==1){
                    mv.addObject("refuseComment", ra.getRefuseComment()+"<br>审核未通过，请重新提交材料报名");
                }else if (ra.getStatus()==2){
                    if(ra.getRefuseComment()==null){
                        mv.addObject("refuseComment", "<br>报名已通过");
                    }else{
                        mv.addObject("refuseComment", ra.getRefuseComment()+"<br>报名已通过");
                    }
                }
            }

            return mv;
        }
        return null;
    }

}
